package com.hamster.crmpre.web;

import com.aliyuncs.exceptions.ClientException;
import com.hamster.crmpre.config.JwtProperties;
import com.hamster.crmpre.config.LoginInterceptor;
import com.hamster.crmpre.exception.ExceptionEnum;
import com.hamster.crmpre.exception.LyException;
import com.hamster.crmpre.pojo.PhoneUser;
import com.hamster.crmpre.pojo.Role;
import com.hamster.crmpre.pojo.UserInfo;
import com.hamster.crmpre.service.PhoneUserService;
import com.hamster.crmpre.util.CookieUtils;
import com.hamster.crmpre.util.JwtUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Tarry
 * @create 2019/11/29 9:43
 */
@RestController
public class PhoneUserController {

    @Autowired
    private PhoneUserService userService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private JwtProperties props;
    @Autowired
    private StringRedisTemplate redisTemplate;



    @Value("${wx.config.appid}")
    private String appid;
    @Value("${wx.config.secret}")
    private String secret;

    @GetMapping("test")
    public ResponseEntity<String>  testLogin(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("1");
        user.setOpenid("123456789");
        user.setPhone("15127812872");
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }
    @GetMapping("test2")
    public ResponseEntity<String>  test2Login(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("2");
        user.setOpenid("00000000001");
        user.setPhone("15127812871");
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }

    /**
     * 前端测试登录接口
     * @param request
     * @param response
     * @return
     */
    @GetMapping("test3")
    public ResponseEntity<String>  test3Login(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("1217254893043732481");
        user.setOpenid("o2JyHwklfvg_SYXJ9GXcGPU9d6FQ");
        user.setPhone("15732033421");//12345672333    15732033421
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }

    /**
     * 前端测试登录接口  丹阳
     * @param request
     * @param response
     * @return
     */
    @GetMapping("test4")
    public ResponseEntity<String>  test4Login(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("4");
        user.setOpenid("444444444");
        user.setPhone("10010100101");
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }

    @GetMapping("test8")//分公司登录
    public ResponseEntity<String>  test8Login(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("5");
        user.setOpenid("5555555");
        user.setPhone("11111322222");
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }


    @GetMapping("testzn")
    public ResponseEntity<String>  testznLogin(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("88");
        user.setOpenid("12345678910");
        user.setPhone("18932573827");
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }


    /**
     * 前端测试登录接口  zn
     * @param request
     * @param response
     * @return
     */
    @GetMapping("test5")
    public ResponseEntity<String>  test5Login(HttpServletRequest request,HttpServletResponse response){
        String token = null;
        PhoneUser user = new PhoneUser();
        user.setId("3");
        user.setOpenid("00000000002");
        user.setPhone("18203319831");
        if (user != null){ //用户存在

            token= this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
            return ResponseEntity.ok(token);

        }
        return ResponseEntity.ok("测试错误");
    }

    @GetMapping("login")
    public ResponseEntity<String> userLogin(@RequestParam("code") String code,HttpServletRequest request,HttpServletResponse response){
        System.out.println("code---------------"+code);
        JSONObject jsonObject = this.getopenId(code);
        String openid = jsonObject.get("openid").toString();
        String token = null;
        //通过openid查询数据库是否有此用户

        PhoneUser user = userService.getUserByOpenId(openid);
        if (user != null){ //用户存在

            token = this.createToken(user);
            response.setHeader("token",token);
            //将Token写入cookie中
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);

            return ResponseEntity.ok(token);

        }
        //新增用户
        PhoneUser newUser = new PhoneUser();
        newUser.setOpenid(openid);
        PhoneUser user2 = userService.insertUser(newUser);
        token= this.createToken(user2);
        response.setHeader("token",token);

        //将Token写入cookie中
        CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);
        return ResponseEntity.ok(token);

    }

    /**
     * 向手机发送验证码
     * @param phone
     * @return
     */
    @GetMapping("sendPhoneCode")
    public ResponseEntity<Void> sendPhoneCode(@RequestParam String phone){
        //判断该手机是否已经被其他人绑定【如果绑定，抛出异常】
        if (userService.checkPhone(phone)){
            throw new LyException(ExceptionEnum.PHONE_ALREADY_EXISTS);
        }
        //判断该手机号系统后台是否存在，如果不存在 提示:"您不是本公司人员，请联系工作人员开通账号"
        String tip = userService.queryNameByPhone(phone);
        if ("该用户没有绑定手机号 或 系统没有该用户手机号".equals(tip)){
            throw new LyException(ExceptionEnum.YOU_NOT_COMPANY_PEOPLE);
        }


        //发送验证码
        try {
            userService.sendPhoneCode(phone);
        } catch (ClientException e) {
            throw new LyException(ExceptionEnum.PHONE_CODE_FAIL);
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 绑定手机号
     * @param phone
     * @return
     */
    @GetMapping("bindPhone")
    public  ResponseEntity<String> bindPhone(@RequestParam String code,@RequestParam String phone,HttpServletRequest request,HttpServletResponse response){
        //获取redis中的验证码
        String content = redisTemplate.opsForValue().get(phone);//根据key获取缓存中的val
        if (content == null){
            throw new LyException(ExceptionEnum.PHONE_CODE_TIMEOUT);//验证码过期
        }

        if (!content.equals(code)){
            throw new LyException(ExceptionEnum.PHONE_CODE_ERROR);   //抛出 验证码不正确 的异常
        }
        UserInfo loginUser = LoginInterceptor.getLoginUser();
        String openId = loginUser.getOpenid();//openid
        PhoneUser phoneUser = userService.setPhone(openId, phone);//返回 手机登录的对象
        //根据手机登录的对象生成token
        String token= this.createToken(phoneUser);
        response.setHeader("token",token);

        //将Token写入cookie中
        CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), token);


        return ResponseEntity.ok(token);
    }

    //创建token
    private String createToken(PhoneUser user){
        //用户基本信息存入UserInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setOpenid(user.getOpenid());
        if (StringUtils.isBlank(user.getPhone())){
            userInfo.setPhone(null);
            userInfo.setRole("暂无");
            userInfo.setPermission(null);
        }else{
            String phone = user.getPhone();
            Role role = userService.queryUser(phone);
            userInfo.setPhone(phone);
            userInfo.setRole(role.getRole());//设置角色
            userInfo.setPermission(role.getPermission());//设置权限
            userInfo.setUserId(role.getUserId());  //设置用户id
            userInfo.setDepartment(role.getDepartment()); //设置部门
        //    userInfo.setPosition(role.getPosition());   //设置职位
           // userInfo.setPosition("主管");   //设置职位
            userInfo.setProject(role.getProject());     //设置 客户已购买项目名称
           // userInfo.setName(role.getName());          //设置姓名[这里注释，因为中文容易乱码]

        }

        //生成Token
        System.out.println(userInfo);
        try {
            String token = JwtUtils.generateToken(userInfo, props.getPrivateKey(), props.getExpire());
            return token;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.GENERATE_TOKEN_FAIL);
        }
    }

/**
    public ResponseEntity login(String code){
        JSONObject jsonObject = this.getopenId(code);

        if(jsonObject!=null&&!jsonObject.containsKey("openid")) {
            throw new LyException(ExceptionEnum.LOGIN_FAIL); //登录失败
        }
        String openid = (String)jsonObject.get("openid");
        String sessionKey = (String)jsonObject.get("session_key");
        //通过openid查询数据库是否有此用户
        User user = userService.getUserByOpenId(openid);
        if (user != null){ //用户存在
            //返回手机号
            if (user.getPhone() == null){
                jsonObject.put("phone", "");
            }else {
                jsonObject.put("phone",user.getPhone());
            }
            stringRedisTemplate.boundValueOps(openid).set(sessionKey,60, TimeUnit.MINUTES);
            jsonObject.put("userId",user.getId());
            jsonObject.put("dateTime","");
            return ResponseEntity.ok(jsonObject.toString());
        }
//        新增用户
        User newUser = new User();
        newUser.setOpenid(openid);
        User user2 = userService.insertUser(newUser);
        jsonObject.put("phone", "");

        stringRedisTemplate.boundValueOps(openid).set(sessionKey,60, TimeUnit.MINUTES);//存到redis中,设置失效时间
        jsonObject.put("userId", user2.getId());
        jsonObject.put("dateTime","");
        return ResponseEntity.ok(jsonObject.toString());
    }

*/



    //请求微信服务器，获取返回值
    private JSONObject getopenId(String code){
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String jsonData = this.restTemplate.getForObject(url, String.class);
        JSONObject jsonObject= JSONObject.fromObject(jsonData);

        return jsonObject;
    }


    @GetMapping("verify")     //获取cookie使用【@CookieValue注解】
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String token,
                                           HttpServletResponse response,
                                           HttpServletRequest request){
        UserInfo info;
        //解析token
        try {
            //1.解析token
            info = JwtUtils.getUserInfo(props.getPublicKey(), token);
            //2.防止token过期，重新生成token
            String newToken = JwtUtils.generateToken(info, props.getPrivateKey(), props.getExpire());
            //写入Cookie
            CookieUtils.newBuilder(response).maxAge(props.getCookieMaxAge()).request(request).build(props.getCookieName(), newToken);
        } catch (Exception e) {
            //token无效，过期
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return ResponseEntity.ok().body(info);
    }


    /**
     * 查询该手机号对应人的姓名
     * @param phone 手机号
     * @return
     */
    @GetMapping("queryNameByPhone")
    public String queryNameByPhone(@RequestParam String phone){
        return userService.queryNameByPhone(phone);
    }

    /**
     * 查询当前登录人的姓名
     * @return
     */
    @GetMapping("queryNameByPhone2")
    public String queryNameByPhone(){
        String phone = LoginInterceptor.getLoginUser().getPhone();
        return userService.queryNameByPhone(phone);
    }

}
